<template>
  <!-- start 选项 -->
  <div class="form-setting-options">
    <h4>
      选项<el-checkbox
      v-if="hasMultiControl"
      :disabled="!!field.id"
      class="form-select-setting-isMulti"
      :value="field.isMulti"
      @input="update($event, 'isMulti')">{{$t('common.base.multiple')}}
      </el-checkbox>
    </h4>
    <div class="form-select-setting-list">
      <draggable tag="div" class="list-group" :list="options" v-bind="{ animation:380 }" handle=".handle">
        <div v-for="(option, index) in options" :key="useIdAsKey ? option.idKey : index" class="form-select-setting-option">
          <button type="button" class="btn-text handle"> <i class="iconfont icon-tuozhuaipaixu"></i></button>
          <input type="text" :value="option.value" @input="updateOption($event, option)" :maxlength="optionMaxLength">
          <button type="button" class="btn-text form-select-setting-delete" @click="delOption(option, index)"><i class="iconfont icon-minus-fill"></i></button>
          <template v-if="!field.isMulti && !useIdAsKey">
            <button type="button" :class="['btn-text', 'form-select-setting-default',option.isDefault && 'btn-active']" @click="setDefaultOption(option)"> <i class="iconfont icon-check-fill"></i></button>
            <span class="form-select-setting-defaultValue" v-if="option.isDefault">{{$t('common.base.default')}}</span>
          </template>
        </div>
      </draggable> 
    </div>
    <div class="form-setting-group form-select-setting-operation form-select-setting-btnbox">
      <button type="button" class="btn-text" @click="addOption">增加选项</button>
      <div class="btn-divider"></div>
      <button v-if="!useIdAsKey" type="button" class="btn-text" @click="showBatchModal('edit')">{{$t('common.base.bulkEdit')}}</button>
      <button v-if="needPatchAdd" type="button" class="btn-text" @click="showBatchModal('add')">{{$t('common.base.buildAdd')}}</button>
    </div>

    <!-- start 批量添加选项 -->
    <base-modal 
      :title="$t('common.base.buildAddOption')" width="520px" class="form-select-setting-modal"
      :show.sync="batchModalShow" :mask-closeable="false">
      <div class="form-select-setting-batch">
        <textarea :value="optionText" @input="updateOptionText" rows="10"></textarea>
        <div class="form-select-setting-warn" v-if="errMessage">{{errMessage}}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <span class="form-select-tips">{{$t('common.base.everyLinePointToOneOption')}}</span>
        <el-button @click="batchModalShow = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="batchEdit">{{$t('common.base.save')}}</el-button>
      </div>
    </base-modal>
    <!-- end 批量添加选项 -->
  </div>
  <!-- end 选项 -->
</template>

<script>
import {
  SELECT_OPTION_MAX,
  SELECT_OPTION_LENGTH_MAX
} from '@src/component/form/config'

import Platform from '@src/platform';
import draggable from 'vuedraggable';

import _ from 'lodash';

export default {
  name: 'setting-option',
  props: {
    field: {
      type: Object
    },
    update: {
      type: Function
    },
    useIdAsKey: {
      type: Boolean,
      default: false
    },
    hasMultiControl: {
      type: Boolean,
      default: true
    },
    propOptions: {
      type: Object
    },
    needPatchAdd: {
      type: Boolean,
      default: false
    }
  },
  data(){
    let options = this.propOptions.value || this.field.options || [];
    return {
      index: options.length || 0,
      batchModalShow: false, 
      optionText: '', // 批量编辑文本
      errMessage: null,
      batchEditType: 'edit'
    }
  },
  computed: {
    optionMaxLength(){
      return SELECT_OPTION_LENGTH_MAX
    },
    options(){
      return this.propOptions.value || this.field.options || [];
    }
  },
  methods: {
    addOption(){
      if(this.options.length >= SELECT_OPTION_MAX) return Platform.alert(this.$t('common.base.tip.chooseOptionCantMoreThan', {count:SELECT_OPTION_MAX}));

      let options = _.cloneDeep(this.options);
      this.index++;

      let option = {
        value: ``,
        isDefault: false
      }
      if (this.useIdAsKey) {
        option.idKey = `temporary_value_${+new Date() + this.index}`
      }
      options.push(option)

      this.$emit('input', {value: options, prop: 'options'})
    },
    updateOption(event, option){
      option.value = event.target.value;
      
      this.$emit('input', {value: this.field, prop: 'dependencies', operate: 'delete'})
    },
    delOption(option, index){
      if(this.options.length <= 1) return alert(this.$t('common.base.tip.evenHaveOneOption2'))

      // 如果是删除默认值，清空默认值
      if(option.isDefault) this.$emit('input', {value: null, prop: 'defaultValue'});

      let options = _.cloneDeep(this.options);
      options.splice(index, 1);

      this.$emit('input', {value: options, prop: 'options'})
      this.$emit('input', {value: this.field, prop: 'dependencies', operate: 'delete'})
    },
    showBatchModal(type){
      this.optionText = type === 'edit' ? this.options.map(item => item.value).join('\n') : ''
      this.batchModalShow = true;
      this.errMessage = null;
      this.batchEditType = type
    },
    batchEdit(){
      let newValues = this.optionText.split('\n').filter(option => option);
      if(!newValues.length) {
        Platform.alert(this.$t('common.base.tip.evenHaveOneOption'));
        return false;
      }

      this.errMessage = this.validateOptions(newValues);
      if(this.errMessage) return false;

      let newOptions = newValues.map((item, index) => {
        let option = {
          value: item,
          isDefault: false
        }
        let newIndex = this.index + index + 1
        if (this.useIdAsKey) {
          option.idKey = `temporary_value_${+new Date() + newIndex}`
        }
        return option
      });
      // 补全默认值
      if(!this.field.isMulti && !this.useIdAsKey){
        let defaultValue = this.field.defaultValue;
        for(let i = 0; i < newOptions.length; i++){
          let option = newOptions[i];
          let value = option.value
          if(defaultValue == value){
            this.$set(option, 'isDefault', true)
            break;
          }
        }
      }

      if (this.batchEditType === 'add') {
        newOptions = [
          ...this.options,
          ...newOptions
        ]
      }
      this.$emit('input', {value: newOptions, prop: 'options'})
      this.$emit('input', {value: this.field, prop: 'dependencies', operate: 'delete'})

      this.batchModalShow = false;
    },
    updateOptionText(event){
      this.optionText = event.target.value;
    
      let newOption = this.optionText.split('\n');
      this.errMessage = this.validateOptions(newOption);
    },
    validateOptions(opts){
      let options = opts[opts.length - 1] == null ? opts.slice(0, -1) : opts;
      let message = [];
    
      // 验证数量
      if(options.length > SELECT_OPTION_MAX){
        message.push(this.$t('common.base.tip.chooseOptionCantMoreThan', {count:SELECT_OPTION_MAX}));
      }
    
      // 是否有空白项
      if(options.some(item => !item)){
        message.push(this.$t('common.base.tip.cantHaveNullOption'));
      }
    
      // 验证每一项长度
      let errIndex = options.map((item, index) => item.length > SELECT_OPTION_LENGTH_MAX ? index + 1 : -1).filter(item => item != -1);
      if(errIndex.length > 0){
        message.push(this.$t('common.form.preview.relatedCatalog.des5', {data1:errIndex.join('，'),data2:SELECT_OPTION_LENGTH_MAX}));
      }
    
      return message.length > 0 ? message.join('\n') : null;
    },
    // 设置默认值(默认和取消默认可以切换)
    setDefaultOption(option){
      if(this.field.isMulti) return Platform.alert(this.$t('common.form.preview.relatedCatalog.des6'));
      if(!option.value) return Platform.alert(this.$t('common.form.preview.relatedCatalog.des7'));
      let _formState = option.isDefault;

      this.options.forEach(item => item.isDefault = false);
      option.isDefault = !_formState;

      this.$emit('input', {value: this.options, prop: 'options'})
      this.$emit('input', {value: option.value, prop: 'defaultValue'});
    },
  },
  components: {
    draggable
  }
}
</script>